import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hm_show_flutter/api/service/goods_service.dart';
import 'package:hm_show_flutter/constant/string.dart';
import 'package:hm_show_flutter/entity/goods.dart';
import 'package:hm_show_flutter/entity/goods_detail_entity.dart';
import 'package:hm_show_flutter/entity/share.dart';
import 'package:hm_show_flutter/page/goods/detail_swiper.dart';
import 'package:hm_show_flutter/style/style.dart';
import 'package:hm_show_flutter/utils/navigator_util.dart';
import 'package:hm_show_flutter/utils/share_util.dart';
import 'package:hm_show_flutter/utils/toast_util.dart';
import 'package:hm_show_flutter/widgets/cached_image.dart';
import 'package:hm_show_flutter/widgets/empty_view.dart';
import 'package:hm_show_flutter/widgets/loading_dialog.dart';
import 'package:like_button/like_button.dart';

///商品详情
class GoodsDetailPage extends StatefulWidget {
  final int id;

  GoodsDetailPage(this.id);

  @override
  _GoodsDetailPageState createState() => _GoodsDetailPageState();
}

class _GoodsDetailPageState extends State<GoodsDetailPage> {
  GoodsService _goodsService = new GoodsService();
  GoodsDetailDataProduct _data;
  ShareModel _shareModel;
  var _goodsDetailFuture;
  bool _isCollection = false;

  @override
  void initState() {
    super.initState();
    _goodsDetailFuture = _goodsService.getGoodsDetailData(widget.id, (success) {
      GoodsDetailEntity entity = success;
      _data = entity.data.product;
      setState(() {
        _isCollection = _data.isCollection;
        _shareModel = _data.share;
      });
    }, (fail) {});
  }

  void _shareDialog() {
    showModalBottomSheet(
        backgroundColor: Colors.white,
        context: context,
        builder: (BuildContext context) {
          return Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  GestureDetector(
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: <Widget>[
                        Image.asset('images/ic_share_wechat.png'),
                        Text(
                          "微信",
                          style: TextStyle(fontSize: 14),
                        ),
                        Padding(padding: EdgeInsets.only(bottom: 10))
                      ],
                    ),
                    onTap: () async {
                      Navigator.pop(context);
                      ShareUtil.shareWx(_shareModel);
                    },
                  ),
                  GestureDetector(
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: <Widget>[
                        Image.asset('images/ic_share_wxcircle.png'),
                        Text(
                          "朋友圈",
                          style: TextStyle(fontSize: 14),
                        ),
                        Padding(padding: EdgeInsets.only(bottom: 10))
                      ],
                    ),
                    onTap: () async {
                      Navigator.pop(context);
                      ShareUtil.shareWxCircle(_shareModel);
                    },
                  ),
                ],
              ),
              Container(
                color: Colors.grey[100],
                height: 8,
              ),
              GestureDetector(
                child: Container(
                    color: Colors.white,
                    alignment: Alignment.center,
                    padding: EdgeInsets.only(top: 8, bottom: 8),
                    child: Text("取消")),
                onTap: () {
                  Navigator.pop(context);
                },
              ),
            ],
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
          child: AppBar(
            actions: <Widget>[
              GestureDetector(
                onTap: () {
                  if (_shareModel != null) {
                    _shareDialog();
                  }
                },
                child: Padding(
                  padding: const EdgeInsets.only(right: 12),
                  child: _shareModel == null ? Container() : Icon(Icons.share),
                ),
              )
            ],
            iconTheme: IconThemeData(color: Colors.white),
            automaticallyImplyLeading: true,
            centerTitle: true,
            title: Text(
              "商品详情",
              style: TextStyle(color: Colors.white, fontSize: 16.0),
            ),
          ),
          preferredSize: Size.fromHeight(ScreenUtil.instance.height * 0.036)),
      body: FutureBuilder(
          future: _goodsDetailFuture,
          builder: (BuildContext context, AsyncSnapshot asyncSnapshot) {
            switch (asyncSnapshot.connectionState) {
              case ConnectionState.none:
              case ConnectionState.waiting:
                return LoadingDialog();
              default:
                if (asyncSnapshot.hasError)
                  return Container(
                    child: Center(
                      child: Text(
                        Strings.SERVER_EXCEPTION,
                        style: TextStyle(fontSize: 16.0),
                      ),
                    ),
                  );
                else
                  return _detailView();
            }
          }),
      floatingActionButton: _data != null ? _likeButton() : Container(),
    );
  }

  Widget _likeButton() {
    return LikeButton(
      size: 32,
      isLiked: _isCollection,
      onTap: (bool isLiked) {
        return onLikeButtonTap(isLiked, widget.id);
      },
      mainAxisAlignment: MainAxisAlignment.end,
      crossAxisAlignment: CrossAxisAlignment.end,
      likeBuilder: (bool isLiked) {
        return Container(
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(2.0),
              boxShadow: [
                BoxShadow(
                    color: Colors.black12,
                    blurRadius: 15.0, //阴影模糊程度
                    spreadRadius: 0.1 //阴影扩散程度
                    )
              ]),
          child: Icon(
            Icons.favorite,
            color: isLiked ? Colors.red : Colors.white,
            size: 32,
          ),
        );
      },
    );
  }

  Future<bool> onLikeButtonTap(bool isLiked, int id) {
    return _goodsService.goodsCollection(isLiked, id, (success) {},
        onFail: (fail) {});
  }

  Widget _detailView() {
    if (_data == null) {
      return EmptyView();
    }

    return SingleChildScrollView(
      padding: EdgeInsets.only(bottom: 60),
      child: Column(
        children: <Widget>[
          DetailSwiperView(_data.urls, ScreenUtil.screenWidthDp),
          Padding(
            padding: EdgeInsets.only(top: 10.0),
          ),
          Container(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Padding(
                  padding: const EdgeInsets.only(left: 8),
                  child: _data.name == null?Container():Text(
                    _data.name,
                    style: TextStyle(
                        fontSize: 16.0,
                        color: Colors.black54,
                        fontWeight: FontWeight.bold),
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(top: 6.0),
                ),
                Padding(
                  padding: const EdgeInsets.only(left: 8),
                  child: _data.price == null?Container():Text(
                    "售价：${_data.price} ¥",
                    style: TextStyle(
                      color: Colors.red,
                      fontSize: 14.0,
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(left: 8, right: 8),
                  child: _data.description == null?Container():Html(data: _data.description),
                ),
                Padding(
                  padding: EdgeInsets.only(top: 4.0),
                ),
                _data.parameterMap == null || _data.parameterMap.isEmpty
                    ? Divider()
                    : Container(
                        child: Column(
                          children: <Widget>[
                            Text(
                              Strings.COMMODITY_PARAMETERS,
                              style: TextStyle(
                                color: Colors.black54,
                                fontSize: 17.0,
                              ),
                            ),
                            Padding(
                              padding: EdgeInsets.only(top: 6.0),
                            ),
                            _attributeView(_data.parameterMap),
                          ],
                        ),
                      ),
                Padding(
                  padding: EdgeInsets.only(top: 15.0),
                ),
                _attachList(_data.attach),
              ],
            ),
          )
        ],
      ),
    );
  }

  //商品属性Widget
  Widget _attributeView(List<GoodsDetailDataProductParametermap> parameter) {
    return ListView.builder(
        physics: NeverScrollableScrollPhysics(),
        shrinkWrap: true,
        itemCount: parameter.length,
        itemBuilder: (BuildContext context, int index) {
          return _attributeItemView(parameter[index]);
        });
  }

  Widget _attributeItemView(GoodsDetailDataProductParametermap attribute) {
    return Container(
        margin: EdgeInsets.only(left: 10, right: 10, top: 6, bottom: 6),
        decoration: BoxDecoration(
            color: Colors.grey[100], borderRadius: BorderRadius.circular(5.0)),
        padding: EdgeInsets.all(6.0),
        child: Row(
          children: <Widget>[
            Expanded(
              flex: 2,
              child: attribute.name == null?Container():Text(
                attribute.name,
                style: TextStyle(color: Colors.black54, fontSize: 14.0),
              ),
            ),
            Expanded(
                flex: 4,
                child: Container(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    attribute.value,
                    style: TextStyle(color: Colors.grey, fontSize: 14.0),
                  ),
                )),
          ],
        ));
  }

  Widget _attachList(List<GoodsDetailDataProductAttach> list) {
    if (list == null || list.isEmpty) {
      return Divider();
    }
    return ListView.builder(
        physics: NeverScrollableScrollPhysics(),
        shrinkWrap: true,
        itemCount: list.length,
        itemBuilder: (BuildContext context, int index) {
          return _attachItemView(list[index]);
        });
  }

  Widget _attachItemView(GoodsDetailDataProductAttach attach) {
    return attach == null
        ? Container()
        : Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Container(
                height: 40.0,
                alignment: Alignment.center,
                color: Colors.grey[100],
                child: attach.subtitle == null?Container():Text(
                  attach.subtitle,
                  style: TextStyle(color: Colors.black54, fontSize: 16),
                ),
              ),
              Container(
                padding: EdgeInsets.all(5.0),
                child: attach.xList == null || attach.xList.isEmpty
                    ? EmptyView(
                        topPadding: 10,
                      )
                    : GridView.builder(
                        shrinkWrap: true,
                        itemCount: attach.xList.length,
                        physics: NeverScrollableScrollPhysics(),
                        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 2, childAspectRatio: 0.90),
                        itemBuilder: (BuildContext context, int index) {
                          return _getGridViewItem(context, attach.xList[index]);
                        }),
              )
            ],
          );
  }

  Widget _getGridViewItem(BuildContext context, GoodsModel model) {
    return Container(
      child: InkWell(
        onTap: () {
          NavigatorUtils.goGoodsDetailPage(context, model.id);
        },
        child: Card(
          elevation: 2.0,
          margin: EdgeInsets.all(6.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Expanded(
                  child: CachedImageView(double.infinity,
                      ScreenUtil.instance.setHeight(200.0), model.url)),
              Padding(
                padding: EdgeInsets.only(top: 4.0),
              ),
              Container(
                padding: EdgeInsets.only(left: 4.0, top: 4.0),
                alignment: Alignment.centerLeft,
                child: model.name == null?Container():Text(
                  model.name,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(color: Colors.black54, fontSize: 14.0),
                ),
              ),
              Padding(
                padding: EdgeInsets.only(top: 4.0),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
